package com.estar.assistsurvy.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.estar.assistsurvy.R;
import com.estar.assistsurvy.adapter.MessageListViewAdapter;
import com.estar.assistsurvy.adapter.MessageTypeListAdapter;
import com.estar.assistsurvy.entity.MessageList;
import com.estar.assistsurvy.entity.RequestChangeMessageStatus;
import com.estar.assistsurvy.entity.RequestDeleteMessage;
import com.estar.assistsurvy.entity.RequestGetMessage;
import com.estar.assistsurvy.entity.ResponseMsg;
import com.estar.assistsurvy.entity.ResponseQueryMessage;
import com.estar.assistsurvy.thread.ChangeMessageStatusThread;
import com.estar.assistsurvy.thread.DeleteMessageThread;
import com.estar.assistsurvy.thread.GetMessageListThread;
import com.estar.assistsurvy.utils.ExitUtils;
import com.estar.assistsurvy.utils.MightypleUtil;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;

public class MessagesActivity extends BaseActivity implements OnClickListener,OnRefreshListener
,OnItemClickListener,OnItemLongClickListener{

	private LinearLayout returnBack,msgStyle,recTime;
	private SwipeRefreshLayout id_swipe_ly;
	private ListView id_listview;
	private MessageListViewAdapter adapter;
	private String uuid,deviceId,type,receiveDate;
	private SharedPreferences preferences;
	private List<MessageList> messageList;
	private MessageList selectMessage;
	private ProgressDialog progressDialog;
	private Intent intent;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(progressDialog!=null){
				progressDialog.dismiss();
			}
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;

			case 0:
				ResponseQueryMessage queryMessage=new ResponseQueryMessage();
				queryMessage=(ResponseQueryMessage) msg.obj;
				if(queryMessage.getCode().equals("1")){
					messageList=queryMessage.getMessageList();
//					if(messageList==null||messageList.size()==0||messageList.equals("")){
//						showShortToast("当前信息列表为空，请稍后再试!");
//					}else{
						adapter=new MessageListViewAdapter(messageList, MessagesActivity.this);
						id_listview.setAdapter(adapter);
						id_swipe_ly.setRefreshing(false);
//					}

				}else if(queryMessage.getCode().equals("0")){
					showShortToast(queryMessage.getMessages());
				}else if(queryMessage.getCode().equals("2")){
					ExitUtils.Unlogin(MessagesActivity.this, queryMessage.getMessages());
				}
				break;
				
			case 1:
//				ResponseMsg message1=new ResponseMsg();
//				message1=(ResponseMsg) msg.obj;
//				showShortToast(message1.getMessages());
				
				break;
				
			case 2:
				ResponseMsg message2=new ResponseMsg();
				message2=(ResponseMsg) msg.obj;
				if(message2.getCode().equals("2")){
					ExitUtils.Unlogin(MessagesActivity.this, message2.getMessages());
					return;
				}
				showShortToast(message2.getMessages());
				messageList.remove(selectMessage);
				adapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		};
	};

	private AlertDialog.Builder builder;
	private LayoutInflater inflater;
	private View dialogView;
	private ListView select_messageType;
	private ArrayList<String> list;
	private MessageTypeListAdapter typeAdapter;
	private Calendar calendar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_messages);
		initView();
	}

	@SuppressWarnings("deprecation")
	private void initView(){
		returnBack=find(R.id.returnBack);
		returnBack.setOnClickListener(this);
		msgStyle=find(R.id.msgStyle);
		msgStyle.setOnClickListener(this);
		recTime=find(R.id.recTime);
		recTime.setOnClickListener(this);
		calendar=Calendar.getInstance();
		
		id_swipe_ly=find(R.id.id_swipe_ly);
		id_listview=find(R.id.id_listview);
		id_listview.setOnItemClickListener(this);
		id_listview.setOnItemLongClickListener(this);
		id_swipe_ly.setOnRefreshListener(this);
		id_swipe_ly.setColorScheme(android.R.color.holo_green_dark, android.R.color.holo_green_light,
				android.R.color.holo_orange_light, android.R.color.holo_red_light);
		id_swipe_ly.setRefreshing(true);

		preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
		uuid=preferences.getString("uuid", "");
		deviceId=MightypleUtil.getDeviceId(MessagesActivity.this);
		type="";
		receiveDate="";
		progressDialog=ProgressDialog.show(this, null, "获取消息列表…", false, true);
		RequestGetMessage getMessage=new RequestGetMessage(deviceId, uuid, type, receiveDate);
		Log.i("wl", "平台信使"+getMessage.toString());
		new GetMessageListThread(MessagesActivity.this, handler, getMessage).start();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.returnBack:
			finish();
			break;

		case R.id.msgStyle:
//			dialog=new AlertDialog.Builder(MessagesActivity.this, AlertDialog.THEME_HOLO_LIGHT)
//			.setItems(new String[]{"系统通知","案件通知"}, new DialogInterface.OnClickListener() {
//
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					
//					type=String.valueOf(which+1);
//					RequestGetMessage getMessage=new RequestGetMessage(deviceId, uuid, type, receiveDate);
//					new GetMessageListThread(MessagesActivity.this, handler, getMessage).start();
//					type="";
//				}
//			})
//			.create();
//			dialog.show();
			inflater=LayoutInflater.from(this);
			dialogView=inflater.inflate(R.layout.messagetype_layout, null);
			select_messageType=(ListView) dialogView.findViewById(R.id.select_messageType);
			list=new ArrayList<>();
			list.add("全部");
			list.add("系统通知");
			list.add("案件通知");
			typeAdapter=new MessageTypeListAdapter(list, MessagesActivity.this);
			select_messageType.setAdapter(typeAdapter);
			preferences=getSharedPreferences("messageType", MODE_PRIVATE);
			final Editor editor=preferences.edit();
			int messagetype=preferences.getInt("messageType", -1);
			if(messagetype!=-1){
				typeAdapter.setSelectItem(messagetype);
				typeAdapter.notifyDataSetChanged();
			}else {
				typeAdapter.setSelectItem(0);
				typeAdapter.notifyDataSetChanged();
			}
			
			builder=new AlertDialog.Builder(MessagesActivity.this, AlertDialog.THEME_HOLO_LIGHT)
			.setView(dialogView);
			final AlertDialog dialog=builder.create();
			Window dialogWindow=dialog.getWindow();
			WindowManager.LayoutParams params=dialogWindow.getAttributes();
			dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);

	        /*
	         * lp.x与lp.y表示相对于原始位置的偏移.
	         * 当参数值包含Gravity.LEFT时,对话框出现在左边,所以lp.x就表示相对左边的偏移,负值忽略.
	         * 当参数值包含Gravity.RIGHT时,对话框出现在右边,所以lp.x就表示相对右边的偏移,负值忽略.
	         * 当参数值包含Gravity.TOP时,对话框出现在上边,所以lp.y就表示相对上边的偏移,负值忽略.
	         * 当参数值包含Gravity.BOTTOM时,对话框出现在下边,所以lp.y就表示相对下边的偏移,负值忽略.
	         * 当参数值包含Gravity.CENTER_HORIZONTAL时
	         * ,对话框水平居中,所以lp.x就表示在水平居中的位置移动lp.x像素,正值向右移动,负值向左移动.
	         * 当参数值包含Gravity.CENTER_VERTICAL时
	         * ,对话框垂直居中,所以lp.y就表示在垂直居中的位置移动lp.y像素,正值向右移动,负值向左移动.
	         * gravity的默认值为Gravity.CENTER,即Gravity.CENTER_HORIZONTAL |
	         * Gravity.CENTER_VERTICAL.
	         */
			params.x = 100; // 新位置X坐标
			params.y = 170; // 新位置Y坐标
			params.width = 140; // 宽度
			params.height = 120; // 高度
			params.alpha = 0.9f; // 透明度

	        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
	        // dialog.onWindowAttributesChanged(lp);
	        dialogWindow.setAttributes(params);
			dialog.show();
			select_messageType.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					// TODO Auto-generated method stub
					typeAdapter.setSelectItem(position);
					adapter.notifyDataSetChanged();
					
					editor.putInt("messageType", position);
					editor.commit();
					if(position==0){
						type="";
					}else{
						type=String.valueOf(position);
					}
					RequestGetMessage getMessage=new RequestGetMessage(deviceId, uuid, type, receiveDate);
					new GetMessageListThread(MessagesActivity.this, handler, getMessage).start();
					dialog.dismiss();
					dialog.cancel();
				}
			});
			break;

		case R.id.recTime:
			new DatePickerDialog(MessagesActivity.this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {

				@Override
				public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
					// TODO Auto-generated method stub
					// 更新EditText控件日期 小于10加0
					receiveDate=new StringBuilder()
							.append(year)
							.append("-")
							.append((month + 1) < 10 ? "0"
									+ (month + 1) : (month + 1))
							.append("-")
							.append((dayOfMonth < 10) ? "0" + dayOfMonth : dayOfMonth).toString();
					
					RequestGetMessage getMessage=new RequestGetMessage(deviceId, uuid, type, receiveDate);
					new GetMessageListThread(MessagesActivity.this, handler, getMessage).start();
					receiveDate="";
				}
			}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
			
			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		preferences=getSharedPreferences("messageType", MODE_PRIVATE);
		preferences.edit().clear().commit();
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		progressDialog=ProgressDialog.show(this, null, "获取消息列表…", false, true);
		RequestGetMessage getMessage=new RequestGetMessage(deviceId, uuid, type, receiveDate);
		new GetMessageListThread(MessagesActivity.this, handler, getMessage).start();
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		selectMessage=messageList.get(position);
		new AlertDialog.Builder(MessagesActivity.this, AlertDialog.THEME_HOLO_LIGHT)
		.setMessage("是否删除消息？")
		.setPositiveButton("是", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				progressDialog=ProgressDialog.show(MessagesActivity.this, null, "删除信息…", false, true);

				RequestDeleteMessage deleteMessage=new RequestDeleteMessage(deviceId, uuid, selectMessage.getId());
				new DeleteMessageThread(MessagesActivity.this, handler, deleteMessage).start();
			}
		})
		.setNegativeButton("否", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		})
		.create()
		.show();
		
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		selectMessage=messageList.get(position);
		if(selectMessage.getIsRead().equals("0")){
//			adapter.setClickItem(position);
			messageList.get(position).setIsRead("1");
			adapter.notifyDataSetChanged();
			RequestChangeMessageStatus changeStatus=new RequestChangeMessageStatus(deviceId, uuid, selectMessage.getId());
			Log.i("wl", "消息已读请求"+changeStatus.toString());
			new ChangeMessageStatusThread(MessagesActivity.this, handler, changeStatus).start();
		}
		intent=new Intent(MessagesActivity.this, ReadMessageActivity.class);
		intent.putExtra("content", selectMessage.getMessage());
		startActivity(intent);
		overridePendingTransition(R.anim.zoom_in, R.anim.zoom_out); 
	}
}
